//
//  ZJAlipayViewController.m
//  ShangHaiHuDongApp
//
//  Created by ZJ on 2018/7/4.
//  Copyright © 2018年 刘应平. All rights reserved.
//

#import "ZJAlipayViewController.h"
#import <AlipaySDK/AlipaySDK.h>
@interface ZJAlipayViewController ()<UIWebViewDelegate>
/** webView */
@property (nonatomic, strong) UIWebView *webView;
@end

@implementation ZJAlipayViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.titlelabel.text = self.titleString;
    [self.view addSubview:self.webView];
}

#pragma mark - UIWebView 协议方法
- (void)webViewDidFinishLoad:(UIWebView *)webView{
    [YJProgressHUD hide];
   
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    __weak typeof(self) weakSelf = self;
    //    新版本的H5拦截支付对老版本的获取订单串和订单支付接口进行合并，推荐使用该接口
    BOOL isIntercepted = [[AlipaySDK defaultService] payInterceptorWithUrl:[request.URL absoluteString] fromScheme:@"SBDJY" callback:^(NSDictionary *result) {
        // 处理支付结果
        NSLog(@"%@", result);
        // isProcessUrlPay 代表 支付宝已经处理该URL
        if ([result[@"isProcessUrlPay"] boolValue]) {
            // returnUrl 代表 第三方App需要跳转的成功页URL
            NSString* urlStr = result[@"returnUrl"];
            dispatch_async(dispatch_get_main_queue(), ^{
                weakSelf.urlString = urlStr;
            });
        }
    }];
    
    if (isIntercepted) {
        return NO;
    }
    return YES;
}


- (void)webViewDidStartLoad:(UIWebView *)webView{
    
    //    [YJProgressHUD hide];
}
#pragma mark - Setter


- (void)setUrlString:(NSString *)urlString{
    _urlString = urlString;
    NSURLRequest *webRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]
                                                cachePolicy:NSURLRequestReturnCacheDataElseLoad
                                            timeoutInterval:30];
    [self.webView loadRequest:webRequest];
    [YJProgressHUD showMessage:@"加载中..." duration:10 view:self.view];
}

#pragma mark - Getters

- (UIWebView *)webView{
    if (_webView == nil){
        _webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, LP_TopHeight, [UIScreen zj_screenWith], [UIScreen zj_screenHeight] - LP_TopHeight )];
        _webView.delegate = self;
        _webView.dataDetectorTypes = UIDataDetectorTypePhoneNumber | UIDataDetectorTypeLink | UIDataDetectorTypeShipmentTrackingNumber | UIDataDetectorTypeFlightNumber | UIDataDetectorTypeLookupSuggestion;
        _webView.backgroundColor = [UIColor clearColor];
        [_webView setOpaque:YES];
    }
    return _webView;
}

@end
